using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ClimbTracker.BusinessLogic.Entities;
using MySql.Data.MySqlClient;
using System.IO;

namespace ClimbTracker.GUI.TabControls
{
    public partial class CompetitorsTabControl : UserControl
    {

        private int selectedRowIndex = 0;
        private static Competitor _selectedCompetitor = new Competitor();
        private bool isEditingCompetitor = false;
        private ClimbTrackerDataSet.competitorsRow selectedRow = null;


        public static Competitor SelectedCompetitor
        {
            get { return _selectedCompetitor; }
            set { _selectedCompetitor = value; }
        }


        public CompetitorsTabControl()
        {
            InitializeComponent();
        }

        public void UpdateCompetitorScore(int score)
        {
            SelectedCompetitor.Score += score;
            fillCompetitorCard();
            updateRowInDataGridView();
            updateDB("Competitors");
        }


        private void CompetitorsTabControl_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'climbTrackerDataSet.competitors' table. You can move, or remove it, as needed.
            this.competitorsTableAdapter.Fill(this.climbTrackerDataSet.competitors);

            if (competitorsDataGridView.RowCount > 0)
            {
                // Initialize the first row of the dataGridView to be the selected one.
                competitorsDataGridView.Rows[0].Selected = true;
                selectedRowIndex = 0;
                //switchRowHighlighting(selectedRowIndex);
                fillCompetitorDetails(SelectedCompetitor);
                fillCompetitorCard();
            }

            addCompetitorButton.Enabled = true;
            deleteCompetitorButton.Enabled = true;

            saveCompetitorButton.Enabled = false;
            editCompetitorButton.Enabled = true;
            cancelCompetitorButton.Enabled = false;
        }



        /// <summary>
        /// Update the database with all table changes.
        /// This will function makes the database table reflect the dataGridView.
        /// </summary>
        /// <param name="table"></param>
        public void updateDB(String table)
        {
            MySqlConnection myConnection = new MySqlConnection("server=localhost;user id=root;database=climbtracker");
            MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter("Select * from " + table, myConnection);
            MySqlCommandBuilder mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
            mySqlDataAdapter.Update(climbTrackerDataSet, table);
        }


        /// <summary>
        /// Fills the given competitor object with details from the selected row.
        /// </summary>
        /// <param name="competitor"></param>
        private void fillCompetitorDetails(Competitor competitor)
        {
            try
            {
                competitor.CompetitorID = int.Parse(competitorsDataGridView.Rows[selectedRowIndex].Cells["competitorIDDataGridViewTextBoxColumn"].Value.ToString());
            }
            catch
            {
                competitor.CompetitorID = 0;
            }
            competitor.Name = competitorsDataGridView.Rows[selectedRowIndex].Cells["nameDataGridViewTextBoxColumn"].Value.ToString();
            competitor.Age = int.Parse(competitorsDataGridView.Rows[selectedRowIndex].Cells["ageDataGridViewTextBoxColumn"].Value.ToString());
            competitor.Category = competitorsDataGridView.Rows[selectedRowIndex].Cells["categoryDataGridViewTextBoxColumn"].Value.ToString();
            competitor.Nationality = competitorsDataGridView.Rows[selectedRowIndex].Cells["nationalityDataGridViewTextBoxColumn"].Value.ToString();
            competitor.Ranking = int.Parse(competitorsDataGridView.Rows[selectedRowIndex].Cells["rankingDataGridViewTextBoxColumn"].Value.ToString());
            competitor.Score = int.Parse(competitorsDataGridView.Rows[selectedRowIndex].Cells["ScoreDataGridViewTextBoxColumn"].Value.ToString());
            competitor.PicturePath = competitorsDataGridView.Rows[selectedRowIndex].Cells["picturePathDataGridViewTextBoxColumn"].Value.ToString();
        }



        private void browseButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();


            // Update the pictureBox and picture path only if the user selected a picture
            if (ofd.FileName != null && ofd.FileName.Length > 0)
            {
                SelectedCompetitor.PicturePath = ofd.FileName;
                try
                {
                    pictureBox.Load(SelectedCompetitor.PicturePath);
                }
                catch (FileNotFoundException ex)
                {
                    //show error message
                    MessageBox.Show("This competitor's picture file is missing or corrupt:  " + SelectedCompetitor.PicturePath);
                }
                picturePathLabel.Text = SelectedCompetitor.PicturePath;
            }

        }

        private void competitorsDataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            
            // If the selected cell is in the header row, ignore
            if (e.RowIndex == -1)
                return;

            selectForTrackingButton.Enabled = true;
            selectedRowIndex = e.RowIndex;
            selectedRow = (ClimbTrackerDataSet.competitorsRow)climbTrackerDataSet.competitors.Rows[selectedRowIndex];




            //// Validate that there are no missing fields.
            //// If there are some, popup an error message and return so to avoid the selection change.
            //// Differ between two cases: the selected row is the last (adding new competitor) or is any other
            //if (selectedRowIndex != competitorsDataGridView.Rows.Count - 1)
            //{
            //    if (!isMissingFields())
            //    {
            //       updateDataGridView();
            //    }
            //}
            //else
            //{
            //    if (!isMissingFields())
            //    {
            //        addNewRowToDataGridView();
            //        selectedRowIndex++;
            //    }
            //}


            //switchRowHighlighting(e.RowIndex);

            //if (e.RowIndex == competitorsDataGridView.Rows.Count - 1)
            //{
            //    // If the user selected the last row, then he wishes to create a new competitor.
            //    Competitor = new Competitor();
            //}
            //else
            //{
            //    // Fill the local competitor object with the details.
            //    // This object will be used to fill in the form details and also expose them
            //    // to the other tabs in the application.
                fillCompetitorDetails(SelectedCompetitor);
            //}


            fillCompetitorCard();
            
            addCompetitorButton.Enabled = true;
            deleteCompetitorButton.Enabled = true;

            saveCompetitorButton.Enabled = false;
            editCompetitorButton.Enabled = true;
            cancelCompetitorButton.Enabled = false;

        }

        private void addNewRowToDataGridView()
        {
            ClimbTrackerDataSet.competitorsRow newCompetitorRow = climbTrackerDataSet.competitors.NewcompetitorsRow();
            newCompetitorRow.Name = NameTextBox.Text;
            newCompetitorRow.Age = (byte)AgeNumericUpDown.Value;
            newCompetitorRow.Category = CategoryTextBox.Text;
            newCompetitorRow.Nationality = NationalityTextBox.Text;
            newCompetitorRow.Ranking = (byte)rankingNumericUpDown.Value;
            newCompetitorRow.Score = (byte)scoreNumericUpDown.Value;
            newCompetitorRow.PicturePath = picturePathLabel.Text;
            climbTrackerDataSet.competitors.CompetitorIDColumn.AllowDBNull = true;
            climbTrackerDataSet.competitors.AddcompetitorsRow(newCompetitorRow);
        }



        /// <summary>
        /// Fills the selected comptitor's details in the file card.
        /// </summary>
        private void fillCompetitorCard()
        {
            // Fill the text \ numeric fields
            competitorIDLabel.Text = SelectedCompetitor.CompetitorID.ToString();
            competitorIDLabel.Enabled = false;
            NameTextBox.Text = SelectedCompetitor.Name;
            NameTextBox.Enabled = false;
            AgeNumericUpDown.Value = SelectedCompetitor.Age;
            AgeNumericUpDown.Enabled = false;
            CategoryTextBox.Text = SelectedCompetitor.Category;
            CategoryTextBox.Enabled = false;
            NationalityTextBox.Text = SelectedCompetitor.Nationality;
            NationalityTextBox.Enabled = false;
            rankingNumericUpDown.Value = SelectedCompetitor.Ranking;
            rankingNumericUpDown.Enabled = false;
            scoreNumericUpDown.Value = SelectedCompetitor.Score;
            scoreNumericUpDown.Enabled = false;
            picturePathLabel.Text = SelectedCompetitor.PicturePath;
            picturePathLabel.Enabled = false;

            browseButton.Enabled = false;

            // Show the competitor's picture
            if (File.Exists(SelectedCompetitor.PicturePath))
            {
                pictureBox.Load(SelectedCompetitor.PicturePath);
                picturePathLabel.Text = SelectedCompetitor.PicturePath;
            }
            else
            {
                pictureBox.Image = null;
                pictureBox.Invalidate();
                picturePathLabel.Text = "Path to competitor's picture incorrect";
            }
        }

        /// <summary>
        /// Creates a card with default details.
        /// </summary>
        private void fillBlankCompetitorCard()
        {
            // Fill the text \ numeric fields
            //competitorIDLabel.Enabled = false;
            //competitorIDLabel.Text = Competitor.CompetitorID.ToString();
            NameTextBox.Text = "";
            NameTextBox.Enabled = true;
            AgeNumericUpDown.Value = 25;
            AgeNumericUpDown.Enabled = true;
            CategoryTextBox.Text = "";
            CategoryTextBox.Enabled = true;
            NationalityTextBox.Text = "";
            NationalityTextBox.Enabled = true;
            rankingNumericUpDown.Value = 1;
            rankingNumericUpDown.Enabled = true;
            picturePathLabel.Text = "";
            picturePathLabel.Enabled = true;

            browseButton.Enabled = true;
            
            pictureBox.Image = null;
            pictureBox.Invalidate();
            picturePathLabel.Text = "";
            
        }

        /// <summary>
        /// Updates the competitors' dataGridView with the details of the last selected competitor.
        /// </summary>
        private void updateRowInDataGridView()
        {
            selectedRow.Name = NameTextBox.Text;
            selectedRow.Age = (byte)AgeNumericUpDown.Value;
            selectedRow.Category = CategoryTextBox.Text;
            selectedRow.Nationality = NationalityTextBox.Text;
            selectedRow.Ranking = (byte)rankingNumericUpDown.Value;
            selectedRow.Score = (byte)scoreNumericUpDown.Value ;
            selectedRow.PicturePath = picturePathLabel.Text;
            climbTrackerDataSet.competitors.CompetitorIDColumn.AllowDBNull = true;
        }



        /// <summary>
        /// Remove highlight from previously selected row and highlight the new selected row.
        /// </summary>
        //private void switchRowHighlighting(int newSelectedRowIndex)
        //{
        //    competitorsDataGridView.Rows[selectedRowIndex].DefaultCellStyle.BackColor = Color.White;
        //    selectedRowIndex = newSelectedRowIndex;
        //    competitorsDataGridView.Rows[selectedRowIndex].DefaultCellStyle.BackColor = Color.Wheat;
        //}



        /// <summary>
        /// Validates that all competitor fields are full and valid. Returns false if one of the fields
        /// is missing \ incorrect and true otherwise.
        /// </summary>
        /// <returns></returns>
        private bool isMissingFields()
        {
            // Accumulate the missing fields
            String emptyFields = "";
            if (NameTextBox.Text.Trim().Length == 0)
            {
                emptyFields += "Name, ";
            }
            if (AgeNumericUpDown.Value == 0)
            {
                emptyFields += "Age, ";
            }
            if (NationalityTextBox.Text.Trim().Length == 0)
            {
                emptyFields += "Nationality, ";
            }
            if (CategoryTextBox.Text.Trim().Length == 0)
            {
                emptyFields += "Category, ";
            }
            if (rankingNumericUpDown.Value == 0)
            {
                emptyFields += "Climbing Order, ";
            }

            if (emptyFields.Length > 0)
            {
                emptyFields.Trim();
                emptyFields = emptyFields.Substring(0, emptyFields.Length - 2);

                MessageBox.Show("You must fill in the following fields:\n" + emptyFields, "Missing Fields",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }

            foreach (ClimbTrackerDataSet.competitorsRow row in climbTrackerDataSet.competitors)
            {
                if ((row.Ranking == rankingNumericUpDown.Value) && !(isEditingCompetitor == true))
                {
                    MessageBox.Show("The defined climbing order has already been assigned to another competitor\n Please assign different climbing order", "",MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return true;
                }
            }


            return false;
        }

        private void addCompetitorButton_Click(object sender, EventArgs e)
        {
  
            addCompetitorButton.Enabled = false;
            deleteCompetitorButton.Enabled = false;
 
            editCompetitorButton.Enabled = false;
            saveCompetitorButton.Enabled = true;
            cancelCompetitorButton.Enabled = true;
            
            SelectedCompetitor = new Competitor();
            fillBlankCompetitorCard();
            
        }


        


        private void saveCompetitorButton_Click(object sender, EventArgs e)
        {
            if (!isMissingFields())
            {
                if (isEditingCompetitor)
                {
                    updateRowInDataGridView();
                    isEditingCompetitor = false;
                }
                else
                {
                    addNewRowToDataGridView();
                    selectedRowIndex++;
                }

                competitorIDLabel.Enabled = false;
                NameTextBox.Enabled = false;
                AgeNumericUpDown.Enabled = false;
                CategoryTextBox.Enabled = false;
                NationalityTextBox.Enabled = false;
                rankingNumericUpDown.Enabled = false;
                picturePathLabel.Enabled = false;

                browseButton.Enabled = false;

                addCompetitorButton.Enabled = true;
                deleteCompetitorButton.Enabled = true;

                saveCompetitorButton.Enabled = false;
                editCompetitorButton.Enabled = true;
                cancelCompetitorButton.Enabled = false;
                updateDB("Competitors");
            }
        }

        private void cancelCompetitorButton_Click(object sender, EventArgs e)
        {
            addCompetitorButton.Enabled = true;
            deleteCompetitorButton.Enabled = true;

            saveCompetitorButton.Enabled = false;
            editCompetitorButton.Enabled = true;
            cancelCompetitorButton.Enabled = false;

            isEditingCompetitor = false;

            fillCompetitorDetails(SelectedCompetitor);
            fillCompetitorCard();

        }

        private void editCompetitorButton_Click(object sender, EventArgs e)
        {
            addCompetitorButton.Enabled = false;
            deleteCompetitorButton.Enabled = false;

            editCompetitorButton.Enabled = false;
            saveCompetitorButton.Enabled = true;
            cancelCompetitorButton.Enabled = true;

            competitorIDLabel.Enabled = true;
            NameTextBox.Enabled = true;
            AgeNumericUpDown.Enabled = true;
            CategoryTextBox.Enabled = true;
            NationalityTextBox.Enabled = true;
            rankingNumericUpDown.Enabled = true;
            picturePathLabel.Enabled = true;

            browseButton.Enabled = true;

            // Raise editing flag
            isEditingCompetitor = true;
        }


        private void selectForTrackingButton_Click(object sender, EventArgs e)
        {
            // Update the SelectedCompetitor object
            SelectedCompetitor = new Competitor();
            SelectedCompetitor.Name = NameTextBox.Text;
            SelectedCompetitor.Age = int.Parse(AgeNumericUpDown.Value.ToString());
            SelectedCompetitor.Nationality = NationalityTextBox.Text;
            SelectedCompetitor.Category = CategoryTextBox.Text;
            SelectedCompetitor.Ranking = int.Parse(rankingNumericUpDown.Value.ToString());
            SelectedCompetitor.Score = int.Parse(scoreNumericUpDown.Value.ToString());
            SelectedCompetitor.PicturePath = picturePathLabel.Text;

            selectForTrackingButton.Enabled = false;
        }

        private void deleteCompetitorButton_Click(object sender, EventArgs e)
        {
            DataRow rowDel = climbTrackerDataSet.competitors.FindByCompetitorID((uint) SelectedCompetitor.CompetitorID);
            if (rowDel == null)
                return;
            rowDel.Delete();
            updateDB("Competitors");

        }

        private void generateReport_Click(object sender, EventArgs e)
        {
            ClimbTracker.Reports.CompetitionReportForm repform = new ClimbTracker.Reports.CompetitionReportForm();
            repform.Show();
        }

    }
}
